#include "tcp.h"
#include <myHeader.h>
#include <string.h>
#include <sys/socket.h>
#include "command.h"
#include "trans.h"
/* Usage:  */
int main(){              
    
   
    int socketFd= socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(socketFd,-1,"socket");

    struct sockaddr_in serverAddr;
    serverAddr.sin_family=AF_INET;
    serverAddr.sin_port=htons(12349);
    inet_pton(AF_INET,"127.0.0.1",(void *)&serverAddr.sin_addr);
    /* inet_pton(AF_INET,"192.168.56.129",(void *)&serverAddr.sin_addr); */

    int connectRet=connect(socketFd,(struct sockaddr*)&serverAddr,sizeof(serverAddr));
    ERROR_CHECK(connectRet,-1,"connect");
    int epollFd=epoll_create(10);
    epollAdd(epollFd,STDIN_FILENO);
    epollAdd(epollFd,socketFd);
    struct epoll_event readySet[1024];
    train_t *train=(train_t *)calloc(1,sizeof(train_t));
    char fileName[16]={0};
    while(1){
        
        memset(train,0,sizeof(train_t));
        int readyNum=epoll_wait(epollFd,readySet,1024,-1);
        for(int i=0;i<readyNum;++i){
            if(readySet[i].data.fd==socketFd){
                if(commandReturn(socketFd,fileName)){
                    close(socketFd);
                    return 0;
                }
            }
            else{
                memset(fileName,0,sizeof(fileName));
                // 用户输入命令,传给服务端
                char buf[1024]={0};
                ERROR_CHECK(fgets(buf,sizeof(buf),stdin),NULL,"fgets");
                buf[strlen(buf)-1]='\0';
                if(commandRecognition(buf,train)){
                    continue;
                }
                memcpy(fileName,train->argv,train->argvSize);
                send(socketFd,train,sizeof(train_t),0);
            }
        }
    }
    /* printf("before recv in client\n"); */
    /* recvFileFromWorker(socketFd); */
    /* printf("after recv in client\n"); */
    close(socketFd);
    return 0;
}
